/*
 * 这个类中的很多代码其实可以和maillist, mailread中的代码公用，但是考虑到降低代码之间的耦合度（只针对部分界面相关的代码进行了共用，逻辑层的还是单独存在，这样即使这个类不被初始化依然不会影响整个系统的运行）
 * */
var MailSearch = Class.create();
MailSearch.prototype = {
	initialize: function() {
		// 搜索出来的列表ID
		this.searchIdList = [];
		// 缓存用户输入的搜过内容
		this.userInputContent = '';
		// 搜索的关键字
		this.searchWords = [];
		// 会话搜索出来的结果
		this.searchIdMapper = [];
		// 当前页面
		this.page = 0;
		// 搜索到的邮件/会话的总数目
		this.count = 0;
		// 总页数
		this.pagecounttmp = 0;
		// 当前搜索每页显示的数量（默认20）
		this.pagecount = 20;
		// 是否排序
		this._sort = {};
		this._order = {
			sender: 0,
			subject: 0,
			date: 0
		};
		this._order_name = 'date';
		// 当前read页面显示的是否为搜索read
		this.searchReadPanel = false;
		// 用户搜索过的内容放在cookie中的名称
		this.sc = 'search_content';
		// 每次搜索过的字段
		this.oldSearch = '';
		// 是否有历史记录（用户的行为做历史记录）
		this.is_rsh = false;
	},
	initEvent: function() {
		if(!openSearchModule) return false;
		var self = this, mc = mailConference;
        var _tmp_dl = [{
            name: 'firstpage',
            exec: function() {
				var _index = self.page = 0;
				self.getSearchMailById(_index);
            }
        }, {
            name: 'prevpage',
            exec: function() {
				self.page -= 1;
				self.page = self.page < 0 ? 0 : self.page;
				var _index = self.page*self.pagecount;
				self.getSearchMailById(_index);
            }
        }, {
            name: 'nextpage',
            exec: function() {
				self.page += 1;
				var _index = self.page*self.pagecount;
				self.getSearchMailById(_index);
            }
        }, {
            name: 'endpage',
            exec: function() {
				// self.page += 1;
				// self.page = self.page > (self.pagecounttmp - 1) ? self.pagecounttmp - 1 : self.page;
				self.page = self.pagecounttmp - 1;
				var _index = self.page*self.pagecount;
				self.getSearchMailById(_index);
            }
        }, {
            name: 's_delete',
            exec: function() {
                // self.permanentDeleteMailItems();
				self.operateItems({dest: -1, method: 1});
            }
        }, {
            name: 's_delt',
            exec: function(){
                // self.deleteMailItems();
				self.operateItems({dest: 4, method: 1});
            }
        }, {
            name: 's_spam',
            exec: function(){
                // self.spamMailItems();
				self.operateItems({dest: -1, method: 3});
				jsoplog.ucCapture('spammail');
            }
        }, {
			name: 's_move',
			exec: function(EL, event) {
				var l = self.getMailListFolderlist(self.operateItems);
				if(l.length == 0) {
					Tips.show('没有可移至的文件夹', 3);
					return false;
				}
				menu.showMenu(EL, DOM.sohuMailMain, l, 'menu', true, null, event);
			}
		}, {
			name: 'selpage',
			exec: function(EL, event) {
				var menu_page = [];
                var _a = []
                for (var i = 0; i < self.pagecounttmp; i++) {
                   	_a.push(i + 1);
                }
                _a.each(function(item){
                   	menu_page.push({
                       	text: item,
                       	onclick: function(){
							self.page = --item;
							if(i >= 0) self.getSearchMailById(self.page*self.pagecount);
                       	}
                   	})
                });
                
                menu.showMenu(EL.parentNode, DOM.sohuMailMain, menu_page, 'menu menu_sel', true, null, event);
			}
		}, {
			name: 's_sort_sender',
			exec: function() {
				for(var key in self._order) {
					if(key == 'sender') continue;
					self._order[key] = 0;
				}
				if(self._order.sender == 0) {
					self._order.sender = 1;
				} else {
					self._order.sender = 0;
				}
				self._order_name = 'sender';
				self.getSearchMail({
					q: self.searchWords.join(),
					length: self.pagecount
				}, {
					sort: 'sender',
					order: self._order.sender
				});
				/*
				self.getMailPage(self.currentFolder, self._currentPage, null, null, {
					sort: 'sender',
					order: self._order.sender
				});
				*/
			}
		}, {
			name: 's_sort_subject',
			exec: function() {
				for(var key in self._order) {
					if(key == 'subject') continue;
					self._order[key] = 0;
				}
				if(self._order.subject == 0) {
					self._order.subject = 1;
				} else {
					self._order.subject = 0;
				}
				self._order_name = 'subject';
				self.getSearchMail({
					q: self.searchWords.join(),
					length: self.pagecount
				}, {
					sort: 'subject',
					order: self._order.subject
				});
				/*
				self.getMailPage(self.currentFolder, self._currentPage, null, null, {
					sort: 'subject',
					order: self._order.subject
				});
				*/
			}
		}, {
			name: 's_sort_date',
			exec: function() {
				for(var key in self._order) {
					if(key == 'date') continue;
					self._order[key] = 0;
				}
				if(self._order.date == 0) {
					self._order.date = 1;
				} else {
					self._order.date = 0;
				}
				self._order_name = 'date';
				self.getSearchMail({
					q: self.searchWords.join(),
					length: self.pagecount
				}, {
					sort: 'date',
					order: self._order.date
				});
			}
		}];
		
		var _gpcn = Element.getParentNodeByClassName, _gpatr = Element.getParentNodeByAttribute;
		DOM.mailSearch.observe('click', function(event) {
			var el = event.target;
			_tmp_dl.each(function(item) {
				var e = _gpcn(el, item.name);
				if(e) {
					item.exec(e, event);
					Event.stop(event);
				}
			});
			try {
				var e = _gpatr(el, 'mid');
				if(e) {
					self.getMailRead(e.attribute);
					Event.stop(event);
					return false;
				}
			} catch(e) {}
			try {
				var ed = _gpatr(el, 'id');
				if(ed.attribute == 'selectSearchAll') {
					self.setSelectAll(ed.element);
					return false;
				}
			} catch(e) {}
			try {
				if(el.nodeName.toLowerCase() == 'input' && el.getAttribute('unread')) {
					if(el.checked) {
						self.setSelect(el, true);
					} else {
						self.setSelect(el, false);
					}
					return false;
				}
			} catch(e) {}
		}).observe('mouseover', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).addClassName('bt-common-hover');
			(function() {
				var e = _gpcn(el, 's_search_item');
				if(e) e.style.backgroundColor = '#fbf5e6';
			})();
		}).observe('mouseout', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).removeClassName('bt-common-hover');
			(function() {
				var e = _gpcn(el, 's_search_item');
				if(e) e.style.backgroundColor = '';
			})();
		}).observe('mousedown', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).addClassName('bt-common-press');
		}).observe('mouseup', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).removeClassName('bt-common-press');
		});
		
		// read页面的事件监听（本想共用普通模式下的readmail代码，但是考虑到更好的可维护性，搜索的大部分代码还是采用了重写）
		var _tmp_read_dl = [{
            name: 's_rt',
            exec: function(){
				// 返回按钮定位到信件所在的当前列表页面
				self.returnSearchList();
            }
        }, {
            name: 's_rp',
            exec: function(){
                mailRead.replyMail('reply');
            }
        }, {
            name: 's_fw',
            exec: function(){
                mailRead.replyMail('forward');
            }
        }, {
            name: 's_delete',
            exec: function(){
                // mailRead.mailMove(-1);
				self.operateRead({dest: -1, method: 1});
            }
        }, {
            name: 's_delt',
            exec: function(){
                // mailRead.mailMove(4);
				self.operateRead({dest: 4, method: 1});
            }
        }, {
            name: 's_spam',
            exec: function(){
                // mailRead.mailMove(-1, 3)
				self.operateRead({dest: -1, method: 3});
				jsoplog.ucCapture('spammail');
            }
        }, {
            name: 's_unspam',
            exec: function(){
                // mailRead.mailMove(1);
            }
        }, {
            name: 's_print',
            exec: function(){
                mailRead.mailPrint();
            }
        }, {
            name: 's_source',
            exec: function(){
                mailRead.viewMailSource();
            }
        }, {
            name: 's_download',
            exec: function(){
                mailRead.downloadMailSource();
            }
        }, {
            name: 's_prev',
            exec: function(){
                self.getMailRead(PREV_ID);
            }
        }, {
            name: 's_next',
            exec: function(){
                self.getMailRead(NEXT_ID);
            }
        }, {
            name: 's_reply_area',
            exec: function(){
                mailRead.isFastReply();
            }
        }, {
            name: 's_reply_button',
            exec: function(){
                mailRead.replyMail('fastreply');
            }
        }, {
            name: 's_saveaddr',
            exec: function(EL, event){
                mailRead.saveAddr(EL, event);
            }
        }, {
            name: 's_refuse',
            exec: function(EL){
                mailRead.refuseAddr(EL);
            }
        }, {
            name: 's_savealladdr',
            exec: function(EL, event){
                mailRead.saveAllAddr(EL, event);
            }
        }, {
            name: 's_filepreview',
            exec: function(){
                mailRead.focusPreview();
            }
        }, {
            name: 's_ispreview',
            exec: function(EL){
                mailRead.isPreview(EL);
            }
        }, {
			name: 's_star',
			exec: function(EL) {
				mailRead.setStar(EL);
			}
		}, {name: 's_show_blockquote', exec: function(EL, event) {
				var e = EL.nextSibling, en = null;
				while(e) {
					if(e.nodeType == 1 && Element.hasClassName(e, 'sohu_quote')) {
						en = e;
						break;
					}
					e = e.nextSibling;
				}
				if($(en).visible()) {
					EL.innerHTML = '显示引用文字';
					$(en).hide();
				} else {
					EL.innerHTML = '隐藏引用文字';
					$(en).show();
				}
		}},
		// 会话中用到的事件
		{name: 'send_draft', exec: function(EL, event) {
				var rid = Element.getParentNodeByAttribute(EL, 'rid');
				mc.sendMail(parseInt(rid.attribute));
			}},
			{name: 'save_draft', exec: function(EL, event) {
				var rid = Element.getParentNodeByAttribute(EL, 'rid');
				mc.saveMail(parseInt(rid.attribute));
			}},
			{name: 'delt_draft', exec: function(EL, event) {
				var rid = Element.getParentNodeByAttribute(EL, 'rid');
				mc.deltDraftMail(parseInt(rid.attribute));
			}},
		{name: 'draft_cc', exec: function(EL, event) {
				mc.showDraftCC(event, EL);
			}},
			{name: 'draft_bcc', exec: function(EL, event) {
				mc.showDraftBCC(event, EL);
			}},
			{name: 'draft_sub', exec: function(EL, event) {
				mc.showDraftSub(event, EL);
			}},
			{name: 's_isclosefile', exec: function(EL, event) {
				mc.showAttachFile(event, EL);
			}},
			{name: 's_save_addr', exec: function(EL, event) {
				mc.saveAddr(EL, event);
			}},
			{name: 's_addr_refuse', exec: function(EL, event) {
				mc.refuseAddr(event, EL);
			}},
			{name: 's_save_all_addr', exec: function(EL, event) {
				mc.saveAllAddr(event, EL);
			}},
			{name: 's_reply', exec: function(EL, event) {
				mc.replyFunction(event, EL);
			}},
			{name: 's_reply_all', exec: function(EL, event) {
				mc.replyAllFunction(event, EL);
			}},
			{name: 's_forward', exec: function(EL, event) {
				mc.forwardFunction(event, EL);
			}},
			{name: 's_expand_all', exec: function(EL, event) {
				mc.expandAllFunction(event, EL);
			}},
			{name: 's_shrink_all', exec: function(EL, event) {
				mc.shrinkAllFunction(event, EL);
			}},
			{name: 's_filepreview', exec: function(EL, event) {
				mc.attachFilePreview(event, EL);
			}},
			{name: 'reply_notifier', exec: function(EL, event) {
            	var mid = EL.getAttribute('mid');
                if(mid){
                	mc.reply_notifier(EL, 1, mid);
                }
			}}, 
			{name: 'cancel_reply_notifier', exec: function(EL, event) {
            	var mid = EL.getAttribute('mid');
                if(mid){
                    mc.reply_notifier(EL, 0, mid);
                }
            }},
			{name: 'edm_activity', exec: function(EL, event) {
				var exec_event = EL.getAttribute('eventname');
				if(!exec_event || exec_event == '') return false;
				try {
					return new Function('return ' + exec_event)();
				} catch(e) {}
			}},
			{name: 's_show_item', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				mc.isShow(mid);
			}, cevt: ['s_show_info','s_star']},
			{name: 's_bar_show_info', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				mc.isHeadInfoShow(mid, event);
			}},
			{name: 's_bar_showinfo', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				mc.isHeadInfoShow(mid, EL);
			}},
			{name: 's_show_info', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				mc.isHeadInfoShow(mid, EL);
			}},
			{name: 's_bar_reply', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				try {
					if (!mc._editor_content_check('e_' + mid, function(){
						mc.replyMail(mid, 'reply');
					})) 
					return false;
				} catch(e) {}
				mc.replyMail(mid, 'reply');
			}},
			{name: 's_bar_replyall', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				if(!mc._editor_content_check('e_' + mid, function() {
					mc.replyMail(mid, 'replyall');
				})) return false;
				mc.replyMail(mid, 'replyall');
			}},
			{name: 's_bar_forward', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				if(!mc._editor_content_check('e_' + mid, function() {
					mc.replyMail(mid, 'forward');
				})) return false;
				mc.replyMail(mid, 'forward');
			}},
			{name: 's_bar_del', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				if(!mc._editor_content_check('e_' + mid, function() {
					mc.delMail([mid], 'del');
				})) return false;
				mc.delMail([mid], 'del');
			}},
			{name: 's_bar_delete', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				if(!mc._editor_content_check('e_' + mid, function() {
					mc.delMail([mid], 'delete');
				})) return false;
				mc.delMail([mid], 'delete');
			}},
			{name: 's_bar_source', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				mc.sourceMail(mid);
			}},
			{name: 's_bar_download', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				mc.downloadMail(mid);
			}},
			{name: 's_bar_print', exec: function(EL, event) {
				var mid = EL.getAttribute('mid');
				mc.printMail(mid);
			}},
			{name: 's_bar_menu', exec: function(EL, event) {
				var mid = EL.getAttribute('mid'), _item = null;
				mc.currentConference.each(function(item) {
					if(item.rowid == mid) _item = item;
				});
				list = mc.getMenuList(_item);
				menu.showMenu(EL, DOM.sohuMailMain, list, 'dialog_menu', true, null, event);
			}},
			{name: 's_star', exec: function(EL, event) {
				var sid = EL.getAttribute('sid');
				mc._setStar(EL, sid);
			}},
			{name: 's_show_blockquote', exec: function(EL, event) {
				var e = EL.nextSibling, en = null;
				while(e) {
					if(e.nodeType == 1 && Element.hasClassName(e, 'sohu_quote')) {
						en = e;
						break;
					}
					e = e.nextSibling;
				}
				if($(en).visible()) {
					EL.innerHTML = '显示引用文字';
					$(en).hide();
				} else {
					EL.innerHTML = '隐藏引用文字';
					$(en).show();
				}
			}},
			{name: 's_move', exec: function(EL, event) {
				var l = self.getMailListFolderlist(self.operateRead);
				if(l.length == 0) {
					Tips.show('没有可移至的文件夹', 3);
					return false;
				}
				menu.showMenu(EL, DOM.sohuMailMain, l, 'menu', true, null, event);
			}}
		];
		
		// var _gpcn = Element.getParentNodeByClassName, _gpatr = Element.getParentNodeByAttribute;
		DOM.readMail.observe('click', function(event) {
			try {
				if (!self.searchReadPanel) return false;
			} catch(e) {}
			var el = event.target;
			try {
				_tmp_read_dl.each(function(item){
					if(item.cevt) {
						var _flag = false;
						item.cevt.each(function(_item) {
							if(_gpcn(el, _item)) _flag = true;
						});
						if(_flag) return false;
					}
                    try {
						var e = _gpcn(el, item.name);
						if(e) {
							try {
								item.exec(e, event);
							} catch(e) {}
							Event.stop(event);
							return false;
						}
                    } catch (e) { }
                });
			} catch(e) {}
		});
		this.listenSearchInput('sogouInput');
	},
	// 监听用户搜索的输入行为
	listenSearchInput: function(el) {
		var _el = $(el);
		if(!_el) {
			try {
				var _sf = arguments.callee, self = this;
				setTimeout(function() {
					_sf.call(self, el);
				}, 100);
			} catch(e) {}
			return false;
		}
		if(!this.oldSearch || this.oldSearch == '') {
			this.oldSearch = mailcookie.getCookie(this.sc);
		}
		try {
			var l = this.oldSearch.split('|');
			if (!this.searchOldList) {
				this.searchOldList = new AddressFilter(_el, _el.parentNode, l);
				this.searchOldList.entryEndBreak = true;
				this.searchOldList.searchModule = true;
			}
		} catch(e) {}
	},
	// 清空排序
	resetOrder: function() {
		if(this._order_name == 'date' && this._order.date == 0) return false;
		this._sort = {};
		this._order = {
			sender: 0,
			subject: 0,
			date: 0,
			star: 0
		};
		this._order_name = 'date';
	},
	// 用户开始搜索的行为
	// el: string || element --> 搜索输入框的id或者element
	startSearch: function(el) {
		el = $(el);
		try {
			var word = el.value;
			if (word.blank() || !el.getAttribute('isActive')) {
				_dialog.alert({info: '请输入要搜索的关键字，可以是邮件主题或正文中包含的某个词语。'});
				return false;
			}
			this.getSearch(word, true);
			try {
				mailList.clearListCache();
				mailConference.clearListCache();
			} catch(e) {}
		} catch(e) {}
		// 将被搜索过的内容放在cookie中，方便用户的搜索，最多纪录20条
		try {
			var old_search = mailcookie.getCookie(this.sc);
			if(!old_search) old_search = '';
			if(old_search.split('|').indexOf(word) != -1) return false;
			this.oldSearch = old_search + '|' + word;
			mailcookie.setCookie(this.sc, this.oldSearch, 36000000);
		} catch(e) {}
	},
	// 根据不同的模式采用不同的搜索方式
	getSearch: function(word, rsh) {
		this.is_rsh = rsh;
		var params = {};
		this.userInputContent = word;
		if(isConferenceMode) {
			params = {
				q:word,
				length:this.pagecount,
				isConversation:true
			};
		} else {
			params = {
				q:word,
				length:this.pagecount
			};
		}
		this.resetOrder();
		this.page = 0;
		try {
			this.getSearchMail(params);
		} 
		catch (e) {}
		changePanel('mailSearch');
	},
	// 翻页的时候根据不同的模式来得到信件的ID
	getIdList: function(index) {
		var params = {};
		if(isConferenceMode) {
			if(!this.searchIdMapper[index]) return false;
			var list = this.searchIdMapper.slice(index, (index + this.pagecount)), new_list = [];
			list.each(function(item) {
				new_list = new_list.concat(item[1]);
			});
			params = {
				ids: new_list.join(),
				q: this.searchWords.join(),
				isConversation:true
			};
		} else {
			if(!this.searchIdList[index]) return false;
			var list = this.searchIdList.slice(index, (index + this.pagecount)), new_list = [];
			params = {
				ids: list.join(),
				q: this.searchWords.join()
			};
		}
		return params;
	},
	// 邮件搜索翻页用到的接口
	getSearchMailById: function(_index) {
		this.getSearchMail(this.getIdList(_index));
	},
	getSearchMail: function(params) {
		if(typeof params != 'object') return false;
		if(params.q && (typeof params.q != 'string' || params.q == '')) {
			_dialog.alert({info: '请输入要搜索的关键字，可以是邮件主题或正文中包含的某个词语。'});
			return false;
		}
		if(arguments[1] && typeof arguments[1] == 'object') {
			var _sort = arguments[1];
			if(this._sort.sort != _sort.sort || this._sort.order != _sort.order) {
				this._sort = _sort;
			}
		}
		try {
			Object.extend(params, this._sort);
		} catch(e) {}
		try {
			mail_search(params, this.getSearchCallback.bind(this, params), this.getSearchMailFailureCallback.bind(this));
		} catch(e) {}
	},
	// 普通模式的搜索、会话模式的搜索共用相同的列表页面
	getSearchCallback: function(p, ret) {
		if(typeof ret != 'object') {
			this.getSearchMailFailureCallback();
			return false;
		}
		if(ret.ids) this.searchIdList = ret.ids;
		// if(ret.words) this.searchWords = ret.words;
		if(this.userInputContent != '') this.searchWords = this.userInputContent.split(' ');
		if(ret.threadidMapper) this.searchIdMapper = ret.threadidMapper;
		var sl = isConferenceMode ? this.searchIdMapper : this.searchIdList;
		this.sb = isConferenceMode ? '个会话' : '封邮件';
		this.count = sl.length;
		this.pagecounttmp = this.count%this.pagecount > 0 ? parseInt(this.count/this.pagecount) + 1 : parseInt(this.count/this.pagecount);
		hiddenAllPanel();
		DOM.mailSearch.show();
		var table = this.createTable(ret);
		
		var _op = [], mc = mailConference;
		_op.push('<div class="l-area">');
		_op.push(mc.createDeleteEL(true));
		_op.push(mc.createDelEL());
		_op.push(mc.createSpamEL());
		_op.push(mc.createSprEL());
		_op.push(mc.createMoveEL());
		_op.push('</div>');
		_op.push('<div class="r-area">');
		if(this.pagecounttmp == 0 || ((this.page+1) == 1 && (this.page+1) == this.pagecounttmp)) {
			_op.push(mc.createFirstPageEL(true));
			_op.push(mc.createPrevPageEL(true));
			_op.push(mc.createNextPageEL(true));
			_op.push(mc.createEndPageEL(true));
		} else if((this.page+1) == 1) {
			_op.push(mc.createFirstPageEL(true));
			_op.push(mc.createPrevPageEL(true));
			_op.push(mc.createNextPageEL());
			_op.push(mc.createEndPageEL());
		} else if((this.page+1) == this.pagecounttmp) {
			_op.push(mc.createFirstPageEL());
			_op.push(mc.createPrevPageEL());
			_op.push(mc.createNextPageEL(true));
			_op.push(mc.createEndPageEL(true));
		} else {
			_op.push(mc.createFirstPageEL());
			_op.push(mc.createPrevPageEL());
			_op.push(mc.createNextPageEL());
			_op.push(mc.createEndPageEL());
		}
		_op.push(mc.createSelPageEL(this.page+1));
		_op.push('</div>');
		var _opht = _op.join('');
		
		var mailcontent = ['<div class="operate">', _opht, '</div>', '<div class="m-content">', table, '</div>', '<div class="operate2">', _opht, '</div>'].join('');
		DOM.mailSearch.innerHTML = mailcontent;
		try {
			/*
            // 重用会话界面的代码
            var top_bar = null, bottom_bar = null;
            $A(DOM.mailSearch.childNodes).each(function(item){
                if (item.className == 'operate') 
                    top_bar = item;
                if (item.className == 'operate2') 
                    bottom_bar = item;
            });
			var top_bar_r = top_bar.firstChild, bottom_bar_r = bottom_bar.firstChild;
            var mc = mailConference;
            var delete_el_t = mc.createDeleteEL(), del_el_t = mc.createDelEL(), move_el_t = mc.createMoveEL(), spam_el_t = mc.createSpamEL();
            var delete_el_b = delete_el_t.cloneNode(true), del_el_b = del_el_t.cloneNode(true), move_el_b = move_el_t.cloneNode(true), spam_el_b = spam_el_t.cloneNode(true);
            var sprt_el_t = mc.createSprEL(), sprt_el_b = sprt_el_t.cloneNode(true);
			
            top_bar.appendChild(delete_el_t);
            bottom_bar.appendChild(delete_el_b);
			
			$([delete_el_t, delete_el_b]).each(function(item) {
				$(item.firstChild).addClassName('bt-first');
			});
            
            top_bar.appendChild(del_el_t);
            bottom_bar.appendChild(del_el_b);
			
			top_bar.appendChild(spam_el_t);
            bottom_bar.appendChild(spam_el_b);
			
			top_bar.appendChild(sprt_el_t);
            bottom_bar.appendChild(sprt_el_b);
			          
            top_bar.appendChild(move_el_t);
            bottom_bar.appendChild(move_el_b);
               
            
            var f_p_t = mc.createFirstPageEL(), p_p_t = mc.createPrevPageEL(), n_p_t = mc.createNextPageEL(), e_p_t = mc.createEndPageEL(), s_p_t = mc.createSelPageEL(this.page + 1);
            var f_p_b = f_p_t.cloneNode(true), p_p_b = p_p_t.cloneNode(true), n_p_b = n_p_t.cloneNode(true), e_p_b = e_p_t.cloneNode(true), s_p_b = s_p_t.cloneNode(true);
            
            top_bar_r.appendChild(s_p_t);
            bottom_bar_r.appendChild(s_p_b);
            
            if ((this.page + 1) != this.pagecounttmp) {
                top_bar_r.appendChild(e_p_t);
                bottom_bar_r.appendChild(e_p_b);
                top_bar_r.appendChild(n_p_t);
                bottom_bar_r.appendChild(n_p_b);
            }
            if ((this.page + 1) != 1) {
                top_bar_r.appendChild(p_p_t);
                bottom_bar_r.appendChild(p_p_b);
                top_bar_r.appendChild(f_p_t);
                bottom_bar_r.appendChild(f_p_b);
            }
            */
        } catch (e) {}
		changeToolbarStyle('mailList');
		try {
			var _words = this.userInputContent;
			addAjaxHistory('mailSearch/' + base64.encode64(encodeURIComponent(_words)), 'mailSearch.getSearch("' + _words + '")', '邮件搜索', !this.is_rsh);
		} catch(e) {}
	},
	getSearchMailFailureCallback: function() {
		_dialog.alert({info: '系统错误，请重新尝试'});
	},
	createSubHead: function() {
		return '<div style="height:30px;line-height:30px;padding-left:10px;">搜索 <span style="color:red;font-weight:bold;">'+ this.searchWords.join() +'</span> 共找到 '+ this.count + this.sb + '，如下：</div>';
	},
	// 会话列表的title
	createConferenceTitle: function() {
        var str = '',
        scount = (this.page * this.pagecount) + 1,
		ed = scount + this.pagecount - 1,
        ecount = ed < this.count ? ed : this.count,
        cmcount = [scount, ecount].join(' - '),
        mailnum = this.count > 0 ? ['第 <font id="spMailRange">', cmcount, '</font> 封，共 <font id="spMailCount">', this.count, '</font> 个会话'].join('') : '共 <font id="spMailCount"> 0 </font> 个会话';
		str = ['<tr class="top_tr"><td>&nbsp;</td><td><input id="selectSearchAll" name="" type="checkbox" /></td><td colspan=3> 全选 / 取消全选 </td><td colspan=3><div style="float:right;text-align:right;"><span style="margin-right:16px;_margin-right:32px;">', '</span></div></td></tr>'].join(mailnum);
        return str;
    },
	createTable: function(ret) {
        var tableHTML = [];
		var data = {};
		data['star_level'] = 'icon_star' + this._order.star;
		var _sty = this._order[this._order_name] == 1 ? 'order-top' : 'order-bottom';
		data['sort_' + this._order_name] = '<span class="am '+ _sty +'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>';
		
        tableHTML.push(this.createSubHead());
		tableHTML.push('<table border="0" cellpadding="0" cellspacing="0" id="inbox" class="inbox"><tbody>');
		try {
			isConferenceMode ? tableHTML.push(mailCTitleSearch) : tableHTML.push(new Template(mailTitleSearch).evaluate(data));
		} catch(e) {}
		// tableHTML.push('</tbody></table>');
		
		tableHTML.push('<tr><td colspan=9>');
		// tableHTML.push(new Template(mailTitle1).evaluate(data))
		tableHTML.push(this.createMailList(ret.mails));
        tableHTML.push('</td></tr></tbody></table>');
        var x = tableHTML.join('');
        return x;
    },
	// 邮件列表部分
    createMailList: function(ret) {
        if (ret.length == 0) {
            return '<tr><td colspan="9"><h5> 没有搜索到相关的邮件 </h5></td><td></td></tr>';
        }
        var tmpString = [];
        var x, mtime;
        var msgName, folder, isReadClass, attachmentIcon, date, email, folderIcon, sender, size, subject, xname, xaddr, xsubject, content;
        var now = new Date();
        // var y = now.toString().split(' ');
        var cyear = now.getFullYear();
        var cmonth = now.getMonth() + 1;
        var cday = now.getDate();
        var showSenderAddr = mailCfgClass.getProfileContent().showsenderaddr;
        var _len_ = ret.length;
        for (var i = 0; i < _len_; i++) {
            x = ret[i];
			var _is_read = isConferenceMode ? x.unread == 0 : x.have_read;
            if (_is_read) {
                isReadClass = '';
            } else {
                isReadClass = 'noread';
            }
			
            var _tmpFolderIcon = 'icon_open';
            if (x.have_reply) {
                _tmpFolderIcon = 'icon_reply';
            }
            if (x.have_forward) {
                _tmpFolderIcon = 'icon_forward';
            }
            email = x.envelope.from &&
            x.envelope.from.length > 0 ? x.envelope.from[0] : ['', '未知邮件地址'];
            if (!email) email = ['', '未知邮件地址'];
            folderIcon = (x.have_read ? _tmpFolderIcon : 'icon_close');
			var _is_sys_account = getSysAccount(email[1]);
			if(_is_sys_account) folderIcon = _is_sys_account.icon;
			try {
                var in_addr = mailAddressClass.addressHash.contact.email[email[1]];
            } catch (e) {}
            folderIcon = 'am ' + folderIcon;
            var sfrom = formatSysAccount(email);
			xname = (sfrom[0] && sfrom[0] != '') ? sfrom[0] : (in_addr && in_addr != '') ? in_addr : sfrom[0];
			xaddr = sfrom[1];
			sender = isConferenceMode ? mailConference.formatConferenceActor(x).f : getSenderName([xname, xaddr], showSenderAddr);
			xsubject = x.envelope.subject;
			var xnum = isConferenceMode ? (x.rowids.length > 1 ? '('+ x.rowids.length +')' : '') : '',
			mid = isConferenceMode ? x.thread : x.rowid;
			
			subject = (xsubject.strip() == '') ? '无标题' : xsubject;
            date = x.envelope.display_date;
            size = strfsize(x.size);
			attachmentIcon = x.atts.length > 0 ? '<span class="am upload-fileicon"></span>' : '';
			content = x.content.escapeHTML();
			var _atts = x.atts, _atts_name = [];
			_atts && _atts.each(function(item) {
				if(item[3] == 0) return;
				_atts_name.push(item[0]);
			});
			_atts_name = _atts_name.join(', ');
			
			var s_c = [sender, subject, content, _atts_name];
			s_c = this.replaceHeighLight(s_c, this.searchWords);
		 var _tmpString = ['<div class="search-item s_search_item" style="display:block;">'+
		 		'<div class="',isReadClass ,'" style="background-color:transparent;">'+
				'<div style="width:1%;" class="search-item-line"></div>'+
				'<div style="width:3%;" class="search-item-line"><input name="" type="checkbox" value="', mid, '" unread="', _is_read, '" style="margin-top:6px;_margin-top:3px;" /></div>'+
				'<div style="width:3%;" class="search-item-line"><img class="', folderIcon, '" src="', MailConst.ALL, '/spacer.gif" style="margin-top:4px;" /></div>'+
				'<div style="width:20%;" class="search-item-line cursor" mid="', mid, '"><div title="', xaddr, '">', s_c[0], xnum, '</div></div>'+
				'<div style="width:40%;" class="search-item-line cursor" mid="', mid, '"><div style="margin-left:8px;color:', ((!_is_read && _is_sys_account) ? _is_sys_account.color : '') +';" mid="' + mid + '">', s_c[1], '</div></div>'+
				'<div style="width:3%;" class="search-item-line cursor" mid="', mid, '"><div style="margin-left:8px;"></div></div>'+
				'<div style="width:10%;" class="search-item-line cursor" mid="', mid, '"><div>', mailList.getFolderNamebyID(x.folder), '</div></div>'+
				'<div style="width:15%;" class="search-item-line cursor" mid="', mid, '"><div>', date[0], '</div></div>'+
				'<div style="width:4%;" class="search-item-line cursor" mid="', mid, '"><div>', size, '</div></div>'+
				'</div>'+
				'<div>'+
				'<div style="width:7%;" class="search-item-line"></div>'+
				'<div style="width:60%;" class="search-item-line cursor" mid="', mid, '"><div class="search-content">', s_c[2], '</div></div>'+
				'<div style="width:3%" class="search-item-line cursor" mid="', mid, '"><div style="margin-left:8px;">', attachmentIcon, '</div></div>'+
				'<div style="width:28%;" class="search-item-line cursor" mid="', mid, '"><div class="search-content">',s_c[3] , '</div></div>'+
				'</div></div>'].join('');
            tmpString.push(_tmpString);
        }
        return tmpString.join('');
    },
	getMailListFolderlist: function(callback) {
		var l = [], self = this;
        FolderList.each(function(item){
			var _fid = item.folder_id;
			if(_fid == 2 || _fid == 3 || _fid == 4 || _fid == 5 || _fid == -2 || _fid <= -5) return false;
        	l.push({
                text: item.name,
                onclick: function() {
					try {
						callback.call(self, {
							dest: _fid,
							method: 1
						});
					} catch(e) {}
                    return false;
                }
            });
        });
        return l;
	},
	// 会话和普通信件获取上一封、下一封的判断函数
	getPN: function(id) {
		try {
			var obj = {};
			if (isConferenceMode) {
				if (this.searchIdMapper.length == 0) return false;
				this.searchIdMapper.each(function(item, index){
					if (item[0] == id) {
						obj['next'] = this.searchIdMapper[index + 1] ? this.searchIdMapper[index + 1][0] : null;
						obj['prev'] = this.searchIdMapper[index - 1] ? this.searchIdMapper[index - 1][0] : null;
					}
				}.bind(this));
			} else {
				if (this.searchIdList.length == 0) 
					return false;
				var _index = this.searchIdList.indexOf(id);
				obj['next'] = this.searchIdList[_index + 1] ? this.searchIdList[_index + 1] : null;
				obj['prev'] = this.searchIdList[_index - 1] ? this.searchIdList[_index - 1] : null;
			}
			return obj;
		} catch(e) {
			return {
				next: null,
				prev: null
			};
		}
	},
	getMailRead: function(id, is_rsh) {
		id = parseInt(id);
		var pn = this.getPN(id);
		PREV_ID = pn.prev;
		NEXT_ID = pn.next;
		
		try {
			isConferenceMode ? 
				conversation_read({id: id}, function(ret) {
					try {
						mailConference.getMailReadCallback(is_rsh, ret, true);
					} catch(e) {}
					this.searchReadPanel = true;
				}.bind(this)) : 
				mail_read({id: id},  function(ret) {
					try {
						this.getMailReadCallback(is_rsh, ret);
					} catch(e) {}
					this.searchReadPanel = true;
				}.bind(this));
		} catch(e) {}
	},
	getMailReadCallback: function(is_rsh, ret) {
		if (typeof ret != 'object') {
			_dialog.alert({info: '系统错误，请重试！'});
			return false;
		}
		// if(!this.readMailCache['mail_' + ret.rowid]) this.readMailCache['mail_' + ret.rowid] = ret;
		this.currentMail = mailRead.currentMail = ret;
		hiddenAllPanel();
		DOM.readMail.show();
		// 界面相关部分重用读信页面的代码
		mailRead.setCurrentMailRead(ret);
		mailRead.showMailRead(ret, this.searchWords);
		try {
			var _title = ret.envelope.subject.unescapeHTML().strip() == "" ? "无标题" : ret.envelope.subject.unescapeHTML();
			addAjaxHistory('readMail_' + ret.rowid, 'mailSearch.getMailRead(' + ret.rowid + ', true)', _title, is_rsh);
		} catch(e) {}
		try {
			// log记录
			jsoplog.sendPV('readmail');
		} catch(e) {}
	},
	// 设置被选中的元素
	setSelect: function(obj, is_set, is_all) {
		var oc = is_set ? (function(){
			obj.checked = true;
			return Element.addClassName;
		})() : (function(){
			obj.checked = false;
			return Element.removeClassName;
		})();
		try {
			var e = Element.getParentNodeByClassName(obj, 's_search_item');
			if(e) oc(e, 'item_over');
		} catch(e) {}
		if(is_all) return false;
		try {
			var ssa = $('selectSearchAll');
			if(ssa && ssa.checked) ssa.checked = false;
		} catch(e) {}
	},
	setSelectAll: function(obj) {
		try {
			var _j = obj.checked, self = this;
			var _list = $A($('inbox').getElementsByTagName('input')).slice(1);
			_list.each(function(item) {
				self.setSelect(item, _j, true);
			});
		} catch(e) {}
	},
	// 获取被选中的对象
	getSelectItem: function() {
		try {
			var _a = {
				mid: [],
				unread: []
			};
			var _list = $A($('inbox').getElementsByTagName('input')).slice(1);
			_list.each(function(item) {
				if (item.checked) {
					_a.mid.push(parseInt(item.value));
					var _urd = item.unread ? item.unread : item.getAttribute('unread');
					_urd = parseInt(_urd);
					if(_urd) _a.unread.push(_urd);
				}
			});
			return _a;
		} catch(e) {
			return {};
		}
	},
	// 操作被选中的邮件列表(可以是删除，永久删除，移动，垃圾举报)
	// operate: {dest: -1->永久删除;4->删除;other->需要移动到的文件夹ID, method: 1->移动;3->垃圾举报}
	operateItems: function(operate) {
		var _so = this.getSelectItem();
		if(!_so || _so.mid.length == 0) {
			_dialog.alert({info: '请选择您要操作的邮件'});
			return false;
		}
		if(typeof operate != 'object') return false;
		// 如果是会话模式下，通过获取到的thread id list来得到mail id list
		var mail_id_list = [], thread_list = [];
		if(isConferenceMode) {
			this.searchIdMapper.each(function(item) {
				if(_so.mid.include(item[0])) {
					mail_id_list = mail_id_list.concat(item[1]);
				}
			});
		} else {
			mail_id_list = _so.mid;
		}
		var self = this;
		var confunc = function() {
			var params = {
				dest: operate.dest,
				method: operate.method,
				id: mail_id_list
			};
			mail_move(params, function(ret) {
				// 如果是永久删除，或者垃圾举报，将被选中的信件ID从列表中删除
				if(params.dest == -1 || params.method == 3) {
					self.resetList(_so.mid);
				}
				self.getSearchMailById(self.page*self.pagecount);
				Element.insert($('inbox').parentNode, {before: new Template(hintTemplate).evaluate({message: '操作成功！'})});
				try {
					var _t = setTimeout(function() {
						clearTimeout(_t);
						_t = null;
						var _md = $('messageDiv');
						if(_md) _md.parentNode.removeChild(_md);
					}, 3000);
				} catch(e) {}
			});
		};
		if(operate.dest == -1) {
			_dialog.confirm({info: '您真的确定要删除邮件？', click: function() {
				confunc();
			}});
			return false;
		}
		confunc();
	},
	// 读一封搜索出来的邮件，对其进行删除、移动等操作
	operateRead: function(operate) {
		if(typeof operate != 'object') return false;
		var self = this;
		var confunc = function() {
			var _id = isConferenceMode ? (function() {
				var new_id = [];
				mailConference.currentConference.each(function(item) {
					new_id.push(item.rowid);
				});
				return new_id;
			})() : self.currentMail.rowid;
			var params = {
				dest: operate.dest,
				method: operate.method,
				id: _id
			};
			mail_move(params, function(ret) {
				// 如果是永久删除，或者垃圾举报，将被选中的信件ID从列表中删除
				try {
					if (params.dest == -1 || params.method == 3) {
						var _id = isConferenceMode ? mailConference.currentConference[0].thread : self.currentMail.rowid;
						self.resetList([_id]);
					}
				} catch(e) { }
				// self.getSearchMailById(self.page*self.pagecount);
				self.getMailRead(NEXT_ID);
			}.bind(this));
		};
		if(operate.dest == -1) {
			_dialog.confirm({info: '您真的确定要删除邮件？', click: function() {
				confunc();
			}});
			return false;
		}
		confunc();
	},
	// 重新组织搜索结果的列表ID（主要是删除其中一个或者多个元素）
	// del_list: array(被删除的信件ID，或者会话ID)
	resetList: function(del_list) {
		if(del_list.length == 0) return false;
		if(isConferenceMode) {
			var new_list = [];
			this.searchIdMapper.each(function(item) {
				if(del_list.include(item[0])) return false;
				new_list.push(item);
			});
			this.searchIdMapper = new_list;
		} else {
			var _index = 0;
			while(del_list[_index]) {
				var i = this.searchIdList.indexOf(del_list[_index]);
				if(i >= 0) this.searchIdList = this.searchIdList.slice(0, i).concat(this.searchIdList.slice(i+1));
				_index++;
			}
		}
	},
	// 返回到搜索列表
	returnSearchList: function() {
		// 返回按钮定位到信件所在的当前列表页面
		var self = this;
		var _index = isConferenceMode ? (function() {
			var i = 0;
			self.searchIdMapper.each(function(item, index) {
				if(item[0] == mailConference.currentConference[0].thread) i = index;
			});
			return i;
		})() : this.searchIdList.indexOf(this.currentMail.rowid);
		if(_index < 0) return false;
		self.page = parseInt(_index/self.pagecount);
		self.getSearchMailById(self.page*self.pagecount);
	},
	// 匹配高亮显示的结果
	// content: array --> 需要被匹配字段的列表
	// word: array --> 高亮显示的字段列表
	replaceHeighLight: function(content, word) {
		if(!Object.isArray(content) || !Object.isArray(word)) return content;
		var _rep = function(reg, item, c) {
			return c.replace(reg, '<span class="height-light">'+ item +'</span>');
		};
		var _new_content = [];
		content.each(function(item) {
			word.each(function(_item) {
				var _reg = new RegExp(_item, 'ig');
				_new_content.push(_rep(_reg, _item, item));
			});
		});
		return _new_content;
	}
};
var mailSearch = new MailSearch();
